#include "clkGrid.h"

void clkGrid::init(float a_cWidth, float a_cHeight)
{
	m_cWidth = a_cWidth;
	m_cHeight = a_cHeight;
}

void clkGrid::destroy()
{
	for(int i = 0; i < m_cellList.size(); i++)
		m_cellList[i]->m_objList.release();

	m_cellList.release();
	m_cellPool.release();
}

void clkGrid::queueObj(clkObject* a_object)
{
	if(!a_object->m_isCollidable)
		return;

	int blk = 0, idx = 0;
	clkCell* cell = m_cellPool.newData(&blk,&idx);

	cell->m_memBlock = blk;
	cell->m_memIndex = idx;
	cell->m_min.set(
		floor(a_object->m_aabb.m_min.x/m_cWidth),
		floor(a_object->m_aabb.m_min.y/m_cHeight));
	cell->m_max.set(
		floor(a_object->m_aabb.m_max.x/m_cWidth),
		floor(a_object->m_aabb.m_max.y/m_cHeight));
	cell->m_objList.insertBack(a_object);

	if(!a_object->m_isStationary)
	{
		for(int i = 0; i < m_cellList.size(); i++)
		{
			if(overlapAABB(*cell,*m_cellList[i]))
			{
				m_cellList[i]->m_objList.insertBack(a_object);
			}
		}
	}

	m_cellList.insertBack(cell);
}

bool clkGrid::obtainCell(clkCell** a_cell)
{
	if(m_cellList.empty())
		return false;

	*a_cell = m_cellList.removeFront();
	return true;
}

bool clkGrid::removeCell(clkCell** a_cell)
{
	m_cellPool.deleteData(a_cell,
		&(*a_cell)->m_memBlock,
		&(*a_cell)->m_memIndex);
	return true;
}